<template>
  <div class="exam-container">
    <!-- 搜索区域 -->
    <div class="search" v-show="isShowSearch">
      <span>考试名称 </span>
      <el-input placeholder="请输入考试名称" v-model="selectData.examName" />
      <span>考试状态 </span>
      <el-select placeholder="请选择考试状态" v-model="selectData.status">
        <el-option
            v-for="item in examStatus"
            :key="item.value"
            :value="item.value"
            :label="item.label"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="initExamTableData" class="el-button__primary">
        <template #icon>
          <el-icon>
            <Search />
          </el-icon>
        </template>
        查询
      </el-button>
      <el-button @click="refresh" class="el-button__default">
        <template #icon>
          <el-icon>
            <Refresh />
          </el-icon>
        </template>
        重置
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="operation">
      <div class="float_right">
        <el-tooltip :content="isShowSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button circle @click="isShowSearch = !isShowSearch">
            <template #icon>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-button>
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-button circle @click="refresh">
            <template #icon>
              <el-icon>
                <Refresh />
              </el-icon>
            </template>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 考试表格 -->
    <el-table
        row-key="id"
        border
        class="exam-table"
        :data="tableData"
        v-loading="loading"
        :header-cell-class-name="'table-header'"
        :cell-class-name="'cell'"
        highlight-current-row
        fit
        show-overflow-tooltip
    >
      <el-table-column label="考试名称" prop="examName" />
      <el-table-column label="考试代码" prop="examCode" />
      <el-table-column label="考试类型" prop="examType">
        <template #default="scope">
          <el-tag v-if="scope.row.examType===0" size="large" >普通考试</el-tag>
          <el-tag v-if="scope.row.examType===1" type="success" size="large">证书考试</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="考试简介" prop="examDescription" />
      <el-table-column label="考试开始时间" prop="startTime"/>
      <el-table-column label="考试结束时间" prop="endTime"/>
      <el-table-column label="考试状态" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" size="large">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="分数" prop="score"/>
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button
              link
              size="small"
              @click="takeExam(scope.row.id)"
              v-if="scope.row.status === 4"
          >
            <template #icon>
              <svg-icon icon-class="edit" />
            </template>
            去考试
          </el-button>
          <el-button
              link
              size="small"
              @click="viewCertificate(scope.row.id)"
              v-if="scope.row.status === 8"
          >
            <template #icon>
              <svg-icon icon-class="show" />
            </template>
            导出证书
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <div class="pagination-block">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[6, 10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
      <student-exam-componet @refresh="refresh"/>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {Search} from "@element-plus/icons-vue";
import {exportCertificate, savePaperCheck, userExamList} from "@/api/question/exam.js";
import {studentExam} from "@/stores/exam/studentExamStore.js";
import StudentExamComponet from "@/components/exam/StudentExamComponet.vue";
import {ElMessage} from "element-plus";

// 数据定义
const isShowSearch = ref(true);
const loading = ref(false);
const store=studentExam()
// 搜索条件
const selectData = reactive({
  examName: '',
  status: null,
});

// 表格数据
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 考试状态
const examStatus = [
  { value: 3, label: '待考试' },
  { value: 4, label: '考试中' },
  { value: 5, label: '考试结束' },
  { value: 6, label: '待阅卷' },
  { value: 7, label: '待阅卷' },
  { value: 8, label: '考试完成' },
];

onMounted(() => {
  initExamTableData()
})
// 初始化表格数据
const initExamTableData = async () => {
  loading.value = true;

  const res = await userExamList(currentPage.value,pageSize.value,selectData.status,selectData.examName)

  total.value = res.data.total
  tableData.value=res.data.records
  loading.value = false;
};

// 刷新数据
const refresh = () => {
  selectData.examName = '';
  selectData.status = null;
  currentPage.value = 1;
  initExamTableData();
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  if (status === 3) return 'info';
  if (status ===4) return 'warning';
  if (status === 5) return 'success';
  if (status === 6) return 'warning';
  if (status === 7) return 'warning';
  if (status === 8) return 'success';
};

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    0: '待考试' ,
    1: '考试中',
    2: '考试结束',
    3: '待阅卷',
    4: '待阅卷',
    5: '考试完成',
  };
  return statusMap[status-3];
};

// 操作方法
const takeExam = async (id) => {
  //检查是否已交卷
  const res=await savePaperCheck(id)
  if (res.data) {
    store.setExamId(id)
    store.setExamOpen(true)
  }else {
    ElMessage.error("您已交卷，不能重复作答")
  }
};

const viewCertificate = async (id) => {
  const response = await fetch(`/api/exam/exportCertificate/${id}`);
  if (!response.ok) {
    throw new Error('文件下载失败');
  }

  // 获取文件内容
  const blob = await response.blob();

  // 创建临时链接并触发下载
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'certificate.pdf'; // 设置下载文件名
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);

  // 释放URL对象
  window.URL.revokeObjectURL(url);
};

// 分页事件
const handleCurrentChange = (val) => {
  currentPage.value = val;
  initExamTableData();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  initExamTableData();
};
</script>

<style scoped>
.exam-container {
  border: 1px solid var(--el-menu-border-color);
  width: 100vw;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.search {
  display: flex;
  font-size: 12px;
  align-items: center;
}

.search span {
  line-height: 32px;
  margin-right: 8px;
}

.el-input,
.el-select {
  width: 160px;
  height: 32px;
  font-size: 12px;
  margin: 0 8px;
}

.operation {
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.exam-table {
  width: 100%;
}

:deep(.table-header) {
  color: #000000;
  font-size: 1.5vh;
  text-align: center;
  margin: 10px 0;
}

:deep(.cell) {
  text-align: center;
  margin: 10px 0;
}
</style>